{% extends '1.html' %}
{% load static %}
{% block title %}个人中心{% endblock %}

{% block content %}
<style>
    /* 个人中心页面样式 */
    .dashboard-wrapper {
        display: flex;
        gap: 20px;
        max-width: 1200px;
        margin: 20px auto;
    }

    /* 左侧导航栏 */
    .dashboard-sidebar {
        flex: 0 0 250px;
        background-color: #fff;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        height: fit-content;
    }
    .dashboard-sidebar h3 {
        margin-top: 0;
        color: #333;
        border-bottom: 2px solid #ff6b6b;
        padding-bottom: 10px;
        margin-bottom: 20px;
    }
    .sidebar-menu {
        list-style: none;
        padding: 0;
        margin: 0;
    }
    .sidebar-menu li {
        margin-bottom: 10px;
    }
    .sidebar-menu a {
        display: block;
        padding: 12px 15px;
        text-decoration: none;
        color: #555;
        border-radius: 5px;
        transition: background-color 0.3s, color 0.3s;
    }
    .sidebar-menu a:hover,
    .sidebar-menu a.active {
        background-color: #ff6b6b;
        color: #fff;
    }

    /* 右侧内容区 */
    .dashboard-content {
        flex: 1;
        background-color: #fff;
        border-radius: 8px;
        padding: 30px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    .content-header {
        font-size: 24px;
        color: #333;
        margin-bottom: 20px;
        border-bottom: 1px solid #eee;
        padding-bottom: 10px;
    }
    .content-body p {
        line-height: 1.6;
        color: #666;
    }
    .info-item {
        display: flex;
        margin-bottom: 15px;
    }
    .info-label {
        font-weight: bold;
        width: 100px;
        color: #333;
    }
    .info-value {
        color: #555;
    }

    /* === 新增：购物车和订单的样式 === */
    .cart-list, .order-list {
        display: flex;
        flex-direction: column;
        gap: 15px;
    }
    .cart-item, .order-item {
        display: flex;
        align-items: center;
        padding: 15px;
        border: 1px solid #e0e0e0;
        border-radius: 8px;
        gap: 15px;
    }
    .cart-item-image {
        width: 80px;
        height: 80px;
        object-fit: cover;
        border-radius: 4px;
    }
    .cart-item-details {
        flex-grow: 1;
    }
    .cart-item-details h4 {
        margin: 0 0 5px 0;
        font-size: 16px;
    }
    .cart-item-quantity {
        font-size: 14px;
        color: #777;
    }

    .order-item {
        flex-direction: column;
        align-items: flex-start;
    }
    .order-header {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 10px;
        border-bottom: 1px dashed #eee;
    }
    .order-id, .order-date {
        font-size: 14px;
        color: #555;
    }
    .order-status {
        padding: 4px 10px;
        border-radius: 12px;
        font-size: 12px;
        color: white;
    }
    .order-body {
        width: 100%;
        padding-top: 10px;
    }
    .order-item-list {
        list-style: none;
        padding: 0;
        margin: 0 0 10px 0;
    }
    .order-item-list li {
        display: flex;
        justify-content: space-between;
        padding: 5px 0;
    }
    .order-total {
        text-align: right;
        font-weight: bold;
        font-size: 16px;
        color: #333;
    }

    /* 订单状态颜色 */
    .status-pending { background-color: #ffc107; color: #333; } /* 待支付 */
    .status-paid { background-color: #007bff; } /* 已支付 */
    .status-shipping { background-color: #17a2b8; } /* 发货中 */
    .status-received { background-color: #28a745; } /* 已签收 */
    .status-returning { background-color: #dc3545; } /* 退货中 */
</style>

<div class="dashboard-wrapper">
    <!-- 左侧导航栏 -->
    <aside class="dashboard-sidebar">
        <h3>个人中心</h3>
        <ul class="sidebar-menu">
            <li><a href="#" data-section="profile" class="active">个人资料</a></li>
            <li><a href="#" data-section="orders">我的订单</a></li>
            <li><a href="#" data-section="cart">我的购物车</a></li>
            <li><a href="#" data-section="settings">账户设置</a></li>
            <li><a href="#" id="logoutBtn">退出登录</a></li>
        </ul>
    </aside>

    <!-- 右侧内容展示区 -->
    <main class="dashboard-content">
        <div id="content-area">
            <!-- 默认显示加载中 -->
            <p>正在加载内容...</p>
        </div>
    </main>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const DashboardManager = {
            init: function() {
                // 【核心改动】1. 检查 body 是否有用户ID (即是否为登录状态)
                // 假设父模板 1.html 已经设置了 <body data-user-id="{{ user.id|default:'' }}">
                const userId = document.body.dataset.userId;

                if (!userId) {
                    // 如果没有 userId，说明未登录，跳转到登录页
                    alert('您尚未登录，将跳转到登录页');
                    window.location.href = '/shopper/login/'; // 请确保此URL正确
                    return; // 终止后续执行
                }

                // 2. 绑定事件
                this.bindEvents();

                // 3. 加载默认内容 (个人资料)
                this.loadSection('profile');
            },

            bindEvents: function() {
                // 导航栏点击事件
                const menuLinks = document.querySelectorAll('.sidebar-menu a[data-section]');
                menuLinks.forEach(link => {
                    link.addEventListener('click', (e) => {
                        e.preventDefault();
                        menuLinks.forEach(l => l.classList.remove('active'));
                        e.target.classList.add('active');
                        const section = e.target.getAttribute('data-section');
                        this.loadSection(section);
                    });
                });

                // 退出登录事件
                document.getElementById('logoutBtn').addEventListener('click', (e) => {
                    e.preventDefault();
                    this.handleLogout();
                });
            },

            // 通用的 API 请求函数
            // 注意：这里仍然使用 localStorage 中的 token 进行API认证，这是常见做法
            async apiRequest(url) {
                const token = localStorage.getItem('loginPageAuthToken');
                if (!token) {
                    // 如果 token 丢失，也视为未登录
                    alert('登录凭证已丢失，请重新登录');
                    this.handleLogout();
                    return;
                }

                const response = await fetch(url, {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.status === 401) {
                    alert('登录已过期，请重新登录');
                    this.handleLogout();
                    return;
                }

                if (!response.ok) {
                    throw new Error(`请求失败: ${response.statusText}`);
                }

                return await response.json();
            },

            loadSection: async function(sectionName) {
                const contentArea = document.getElementById('content-area');
                contentArea.innerHTML = '<p>正在加载...</p>';

                try {
                    let contentHtml = '';
                    switch (sectionName) {
                        case 'profile':
                            // 【新增】直接从后端渲染用户信息，更安全
                            contentHtml = `
                                <h2 class="content-header">个人资料</h2>
                                <div class="content-body">
                                    <div class="info-item">
                                        <span class="info-label">用户名:</span>
                                        <span class="info-value">{{ user.username }}</span>
                                    </div>
                                    <div class="info-item">
                                        <span class="info-label">邮箱:</span>
                                        <span class="info-value">{{ user.email }}</span>
                                    </div>
                                    <div class="info-item">
                                        <span class="info-label">注册日期:</span>
                                        <span class="info-value">{{ user.date_joined|date:"Y-m-d" }}</span>
                                    </div>
                                </div>
                            `;
                            break;

                        case 'cart':
                            const cartData = await this.apiRequest('/shopper/api/car/');
                            if (!cartData || cartData.length === 0) {
                                contentHtml = `<h2 class="content-header">我的购物车</h2><p>您的购物车还是空的，快去逛逛吧！</p>`;
                            } else {
                                const cartItemsHtml = cartData.map(item => `
                                    <div class="cart-item">
                                        <img src="${item.product.image}" alt="${item.product.name}" class="cart-item-image">
                                        <div class="cart-item-details">
                                            <h4>${item.product.name}</h4>
                                            <p>¥${item.product.price}</p>
                                        </div>
                                        <div class="cart-item-quantity">
                                            <span>数量: ${item.quantity}</span>
                                        </div>
                                    </div>
                                `).join('');
                                contentHtml = `<h2 class="content-header">我的购物车</h2><div class="cart-list">${cartItemsHtml}</div>`;
                            }
                            break;

                        case 'orders':
                            const ordersData = await this.apiRequest('/shopper/api/orders/');
                            if (!ordersData || ordersData.length === 0) {
                                contentHtml = `<h2 class="content-header">我的订单</h2><p>您还没有任何订单。</p>`;
                            } else {
                                const ordersHtml = ordersData.map(order => {
                                    const statusMap = { '待支付': 'pending', '已支付': 'paid', '发货中': 'shipping', '已签收': 'received', '退货中': 'returning' };
                                    const statusClass = `status-${statusMap[order.state] || 'pending'}`;
                                    let itemsHtml = '<p>订单详情加载中...</p>';
                                    if (order.items && Array.isArray(order.items)) {
                                        itemsHtml = order.items.map(item => `<li><span>${item.product_name || '未知商品'}</span><span>数量: ${item.quantity || 0}</span></li>`).join('');
                                    }
                                    return `
                                        <div class="order-item">
                                            <div class="order-header">
                                                <div><div class="order-id">订单号: ${order.id}</div><div class="order-date">${order.created || order.created_at || '未知日期'}</div></div>
                                                <span class="order-status ${statusClass}">${order.state}</span>
                                            </div>
                                            <div class="order-body">
                                                <ul class="order-item-list">${itemsHtml}</ul>
                                                <div class="order-total">总计: ¥${order.price || '0.00'}</div>
                                            </div>
                                        </div>
                                    `;
                                }).join('');
                                contentHtml = `<h2 class="content-header">我的订单</h2><div class="order-list">${ordersHtml}</div>`;
                            }
                            break;

                        case 'settings':
                            contentHtml = `
                                <h2 class="content-header">账户设置</h2>
                                <div class="content-body">
                                    <p>这里可以放置修改密码、绑定手机等功能。</p>
                                </div>
                            `;
                            break;

                        default:
                            contentHtml = '<p>未知页面</p>';
                    }
                    contentArea.innerHTML = contentHtml;
                } catch (error) {
                    console.error('加载内容失败:', error);
                    contentArea.innerHTML = '<p>加载内容失败，请稍后重试。</p>';
                }
            },

            handleLogout: function() {
                // 清除本地存储的认证信息
                localStorage.removeItem('loginPageAuthToken');
                localStorage.removeItem('loginPageRefreshToken');
                localStorage.removeItem('loginPageUserInfo');
                
                // 跳转到登录页
                window.location.href = '/shopper/login/';
            }
        };

        // 初始化个人中心页面
        DashboardManager.init();
    });
</script>
{% endblock content %}
